//index.js
//获取应用实例
import {
    getSellers,
    getBanner,
    getSchool
} from '../../utils/apis';

import {imageBaseUrl} from '../../utils/urlConfig';


var app = getApp();
Page({
    data: {
        hasMore: true,
        loading: false,
        offset: 0,
        sellerList: null,
        imgUrls: [
            // {"img": "https://ws1.sinaimg.cn/large/a2ba043aly1fxlbdglh6dj20u00fw1kx.jpg"},
            // {"img": "https://ws1.sinaimg.cn/large/a2ba043aly1fxlbdh2t7lj20u00fwgw5.jpg"},
            // {"img": "https://ws1.sinaimg.cn/large/a2ba043aly1fxlbdiyn6vj20u00fw7wh.jpg"},
        ],
        scrollTop: 0,
        school: wx.getStorageSync('address').name
    },
    onLoad: function (options) {
        this.setData({
            'school': wx.getStorageSync('address').name
        });
        this.loadData();
    },
    goSchool() {
        wx.navigateTo({
            url: '/pages/address/list'
        });
    },

    loadData() {
        if (this.data.loading) {
            return;
        }
        var {offset} = this.data;
        this.setData({
            loading: true
        });
        var that = this;
        // 获取banner
        getBanner({
            success: (response) => {
                var url = [];
                response.map(x => url.push({'img': imageBaseUrl + x}));
                that.setData({
                    imgUrls: url
                })
            }
        })
        // 获取商家列表
        getSellers({
            data: {
                offset,
                limit: 10,
                school: wx.getStorageSync('address').id
            },
            success(data) {
                data.rows.map(x => {
                    x.avatar = `${imageBaseUrl}${x.avatar}`
                });
                that.setData({
                    sellerList: that.data.sellerList ? that.data.sellerList.concat(data.rows) : data.rows,
                    offset: that.data.offset + 1,
                    hasMore: data.rows.length === 10,
                    loading: false
                });
            }
        });
    },
    invalidateData() {
        // this.setData({
        //   page: 0,
        //   hasMore: true,
        //   loading: false,
        //   shopList: null
        // })
    },
    onReachBottom(e) {
        if (this.data.hasMore && !this.data.loading) {
            this.loadData()
        }
    },
    callback(address) {
        // getApp().setCurrentAddress(address)
        // this.initAddress()
    },
    onShareAppMessage() {
        // return {
        //   title: '首页',
        //   path: '/pages/index/index'
        // }
    },
    onPageScroll(event) {
        this.setData({
            scrollTop: event.scrollTop
        })
    },
    handleShopDetail({currentTarget: {dataset: {current}}}) {
        var currentStr = JSON.stringify(current);
        wx.navigateTo({
            url: `/pages/shop/show?current=${currentStr}`,
        });
    }
});
